package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.PutTouristsBean;
import com.bjesc_b2c.app.appraiset.bean.TouristsBean;
import com.bjesc_b2c.app.appraiset.mvp.presenter.CustomerPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.CustomerPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CustomerView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.orhanobut.logger.Logger;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.TokenBean;

import static com.bjesc_b2c.app.appraiset.R.id.edit_loan_remarks;
import static com.bjesc_b2c.app.appraiset.R.id.iv_return;
import static com.bjesc_b2c.app.appraiset.R.id.rlty_car_price;

/**
 * Created by yidong on 2017/5/23.
 */

public class CustomerInfoActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener,CustomerView {
    @Bind(R.id.tv_client_name)
    EditText clientNameTv;
    @Bind(R.id.tv_client_grade)
    TextView clientGradeTv;
    @Bind(R.id.tv_title)
    TextView title;
    @Bind(R.id.tv_car_on_city)
    TextView cityTv;
    @Bind(R.id.tv_car_price)
    TextView carPriceTv;
    @Bind(R.id.tv_buy_car_time)
    TextView buyCarTimeTv;
    @Bind(R.id.tv_gearbox)
    TextView gearboxTv;
    @Bind(R.id.tv_client_order)
    TextView orderTypeTv;
    @Bind(R.id.tv_car_type)
    TextView carTypeTv;
    @Bind(R.id.tv_car_age)
    TextView carAgeTv;
    @Bind(edit_loan_remarks)//贷款情况的备注
    EditText loanRemarksEdit;
    @Bind(R.id.edit_remarks)
    EditText remarksEdit;
    @Bind(R.id.rg_client_sex)
    RadioGroup radioSex;
    @Bind(R.id.rg_client_loan)
    RadioGroup radioLoan;
    @Bind(R.id.relative_loan_remark)
    RelativeLayout loanRemarkRela;
    @Bind(R.id.iv_return)
    LinearLayout returnLin;
    @Bind(R.id.id_flowlayout)
    TagFlowLayout mFlowLayout;
    private PutTouristsBean infoBean;
    private String cityName;
    private String brandId;
    private String brandName;
    private String sex;
    private String installment;
    private String installment_desc;
    private String license_city;
    private String dispid;//派单的id
    private String status;// 2已完成 3见面未成交 4未见面
    private String content;//派单终止的备注信息
    private String seriesId;
    private String seriesName;
    private String buyCarTime;//预计购车时间
    private String grade;//等级
    private String gearbox;//变速箱
    private CustomerPresenter presenter;
    private int type;
    private LayoutInflater mInflater;
    private List<String> briands =new ArrayList<>();
    private List<String> briandID =new ArrayList<>();
    private List<String> carTypeId =new ArrayList<>();
    private List<String> carAgeId =new ArrayList<>();
    private List<String> carPriceId =new ArrayList<>();
    private TagAdapter adapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_client_info;
    }

    @Override
    protected void initEventAndData() {
        mInflater = LayoutInflater.from(CustomerInfoActivity.this);
        type = getIntent().getIntExtra("TYPE",1);
        title.setText("客户基本信息");
        returnLin.setVisibility(View.VISIBLE);
        radioSex.setOnCheckedChangeListener(this);
        radioLoan.setOnCheckedChangeListener(this);
        adapter = new TagAdapter<String>(briands) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.layout_tag_view,mFlowLayout, false);
                tv.setText(s);
                return tv;
            }
        };
        mFlowLayout.setAdapter(adapter);
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                briandID.remove(position);
                briands.remove(position);
                adapter.notifyDataChanged();
                return true;
            }
        });
    }

    @Override
    protected void createPresenter() {
        dispid = CustomSharedPreferences.getString(this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        presenter = new CustomerPresenterImpl(this);
        presenter.requestCustomer(dispid,type);
        Logger.d("oid==="+dispid + type );
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 设置单选按钮
     * @param text
     * @param group
     */
    private void setRadioButtonSelect(String text, RadioGroup group) {
        if (text.equals("1")) {
            ((RadioButton) group.getChildAt(0)).setChecked(true);
        } else if (text.equals("2")) {
            ((RadioButton) group.getChildAt(1)).setChecked(true);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        switch (checkedId){
            case R.id.rbtn_client_mr:
                sex = "1";
                break;
            case R.id.rbtn_client_ms:
                sex = "2";
                break;
            case R.id.rbtn_loan_yes:
                installment = "1";
                loanRemarkRela.setVisibility(View.VISIBLE);
                break;
            case R.id.rbtn_loan_no:
                installment = "2";
                loanRemarkRela.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void loadStart() {
        showLoading();
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
    }

    @Override
    public void loadFailure() {
        cancelLoading();
    }

    @Override
    public void getCustimerInfo(TouristsBean infoBean) {
        setInfo(infoBean);
    }
    private void setInfo(TouristsBean nfoBean){
        if(nfoBean == null){
            return;
        }else {
            if (!TextUtils.isEmpty(nfoBean.getName())){
                clientNameTv.setText(nfoBean.getName());
            }
            if (!TextUtils.isEmpty(nfoBean.getSex())){
                setRadioButtonSelect(nfoBean.getSex(),radioSex);
            }
            if (!TextUtils.isEmpty(nfoBean.getInstallment())){
                setRadioButtonSelect(nfoBean.getInstallment(),radioLoan);
                if (!TextUtils.isEmpty(nfoBean.getInstallment_desc()) && nfoBean.getInstallment().equals("1")){
                    loanRemarksEdit.setText(nfoBean.getInstallment_desc());
                    loanRemarkRela.setVisibility(View.VISIBLE);
                }
            }
            if (!TextUtils.isEmpty(nfoBean.getTime_name())){
                buyCarTimeTv.setText(nfoBean.getTime_name());
                buyCarTime = nfoBean.getTime();
            }
            if (!TextUtils.isEmpty(nfoBean.getTour_level())){
                if (nfoBean.getTour_level().equals("1")){
                    grade ="1";
                    clientGradeTv.setText("A");
                }else if(nfoBean.getTour_level().equals("2")){
                    grade ="2";
                    clientGradeTv.setText("B");
                }else if(nfoBean.getTour_level().equals("3")){
                    grade ="3";
                    clientGradeTv.setText("C");
                }
            }

            if (!TextUtils.isEmpty(nfoBean.getDispatch().getContent())){
                remarksEdit.setText(nfoBean.getDispatch().getContent());
            }

            if (!TextUtils.isEmpty(nfoBean.getLicense_city_name())){
                cityTv.setText(nfoBean.getLicense_city_name());
                license_city = nfoBean.getLicense_city();
            }
            if (!TextUtils.isEmpty(nfoBean.getGearbox_name())){
                gearboxTv.setText(nfoBean.getGearbox_name());
                gearbox = nfoBean.getGearbox();
            }
            if (nfoBean.getBrand() != null){
                for (int i =0; i<nfoBean.getBrand().size();i++){
                    briands.add(nfoBean.getBrand().get(i).getBrand_name());
                    briandID.add(nfoBean.getBrand().get(i).getBrand_id());
                }
                adapter.notifyDataChanged();
            }

            if (nfoBean.getPrice() != null){
                String price="";
                for (int i =0; i<nfoBean.getPrice().size();i++){
                    carPriceId.add(nfoBean.getPrice().get(i).getPrice_id());
                    if (i == 0){
                        price = nfoBean.getPrice().get(i).getPrice_name();
                    }else{
                        price +="/"+nfoBean.getPrice().get(i).getPrice_name();
                    }
                    carPriceTv.setText(price);
                }

            }
            if (nfoBean.getCar_age() != null){
                String price="";
                for (int i =0; i<nfoBean.getCar_age().size();i++){
                    carAgeId.add(nfoBean.getCar_age().get(i).getAge_id());
                    if (i == 0){
                        price = nfoBean.getCar_age().get(i).getAge_name();
                    }else{
                        price +="/"+nfoBean.getCar_age().get(i).getAge_name();
                    }
                    carAgeTv.setText(price);
                }

            }
            if (nfoBean.getCar_type() != null){
                String price="";
                for (int i =0; i<nfoBean.getCar_type().size();i++){
                    carTypeId.add(nfoBean.getCar_type().get(i).getType_id());
                    if (i == 0){
                        price = nfoBean.getCar_type().get(i).getType_name();
                    }else{
                        price +="/"+nfoBean.getCar_type().get(i).getType_name();
                    }
                    carTypeTv.setText(price);
                }

            }

        }
    }
    @OnClick({R.id.iv_return, R.id.btn_post, R.id.rlty_car_city,rlty_car_price, R.id.tv_add_brand,
            R.id.rlty_order_info,R.id.rlty_car_type,R.id.rlty_buy_car_time,R.id.rlty_car_gearbox,R.id.rlty_car_age,R.id.rlty_grade})
    public void onClick(View view) {
        switch (view.getId()){
            case iv_return:
                finish();
                break;
            case R.id.rlty_car_city:
                Intent intent = new Intent(CustomerInfoActivity.this,CountryVariousCityActivity.class);
                intent.putExtra("cityType",2);
                startIntent(intent,1);
                break;
            case R.id.rlty_car_price:
                Intent intents = new Intent(CustomerInfoActivity.this,MoreCheckActivity.class);
                startIntent(intents,2);
                break;
            case R.id.tv_add_brand://选择品牌
                Intent intentB = new Intent(CustomerInfoActivity.this, SelectCarBrandActivity.class);
                intentB.putExtra("Brand",2);
                startIntent(intentB, RequestAndResultCode.BasicActivityToSelectCarBrandActivity);
                break;
            case R.id.rlty_order_info:
                Intent intento = new Intent(CustomerInfoActivity.this,SelectTypeActivity.class);
                intento.putExtra("SelecType",2);
                startIntent(intento,3);
                break;
            case R.id.rlty_buy_car_time:
                Intent intentType = new Intent(CustomerInfoActivity.this,SelectTypeActivity.class);
                intentType.putExtra("SelecType",4);
                startIntent(intentType,4);
                break;
            case R.id.rlty_car_type:
                Intent intentTy = new Intent(CustomerInfoActivity.this,MoreCheckActivity.class);
                intentTy.putExtra("SelecType",2);
                startIntent(intentTy,7);
                break;
            case R.id.rlty_car_age:
                Intent intenta = new Intent(CustomerInfoActivity.this,MoreCheckActivity.class);
                intenta.putExtra("SelecType",3);
                startIntent(intenta,8);
                break;
            case R.id.rlty_car_gearbox:
                Intent intentBox = new Intent(CustomerInfoActivity.this,SelectTypeActivity.class);
                intentBox.putExtra("SelecType",5);
                startIntent(intentBox,5);
                break;
            case R.id.rlty_grade:
                Intent intentG = new Intent(CustomerInfoActivity.this,SelectTypeActivity.class);
                intentG.putExtra("SelecType",3);
                startIntent(intentG,6);
                break;
            case R.id.btn_post://提交
                modifyInfo();
                presenter.modifyCustimerInfo(CustomerInfoActivity.this,dispid,infoBean,type);
                break;
        }

    }
     private void modifyInfo(){
         if (infoBean == null){
             infoBean = new PutTouristsBean();
         }
         installment_desc= loanRemarksEdit.getText().toString();
         content = remarksEdit.getText().toString();
         infoBean.setLicense_city(license_city);
         infoBean.setSex(sex);
         infoBean.setInstallment(installment);
         infoBean.setInstallment_desc(installment_desc);
         infoBean.setTime(buyCarTime);
         infoBean.setBrand(briandID);
         infoBean.setPrice(carPriceId);
         infoBean.setCar_age(carAgeId);
         infoBean.setCar_type(carTypeId);
         infoBean.setGearbox(gearbox);
         infoBean.setTour_level(grade);
         infoBean.setName(clientNameTv.getText().toString());
         PutTouristsBean.DispatchBean dispatchBean = new PutTouristsBean.DispatchBean();
         dispatchBean.setContent(content);
         infoBean.setDispatch(dispatchBean);
     }

    @Override
    public void onSuccess(TokenBean bean) {//修改资料成功
        if (bean.getStatus_code() == 0){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                        setResult(22);
                        finish();
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         switch (resultCode){
             case RequestAndResultCode.CountryVariousCityActivity_ResultCode_Area:
                 cityName = data.getStringExtra("cityName");
                 license_city = data.getStringExtra("cityId");
                 cityTv.setText(cityName);
                 break;
             case RequestAndResultCode.SelectCarBrandActivity_ResultCode:
                 brandId = data.getStringExtra("brandId");
                 brandName = data.getStringExtra("brandName");
                 seriesId = data.getStringExtra("seriesId");
                 if (!TextUtils.isEmpty(seriesId)){
                     brandId = brandId+ "-" + seriesId;//品牌加车系
                 }
                 seriesName = data.getStringExtra("seriesName");
                 briands.add(brandName+ "-"+seriesName);
                 briandID.add(brandId);
                 adapter.notifyDataChanged();
                 break;
//             case RequestAndResultCode.BIGCARSOURCEPHOTOACTIVITY_BACK_CARENGINEFRAGMENT_RESULT://价格
//                 carPriceTv.setText(data.getStringExtra("typeName"));
//                 carPriceType = data.getStringExtra("typeId");
//                 Logger.d("carPriceType=="+carPriceType);
//                 break;
             case RequestAndResultCode.CAROFFSHELFACTIVITY_BACK_RESULT://购车时间返回
                 buyCarTimeTv.setText(data.getStringExtra("typeName"));
                 buyCarTime = data.getStringExtra("typeId");
                 break;
             case RequestAndResultCode.CarSeriesAcitivty_TO_CarModelActivity://变速箱
                 gearboxTv.setText(data.getStringExtra("typeName"));
                 gearbox = data.getStringExtra("typeId");
                 break;
             case RequestAndResultCode.CarModelActivity_Result://等级
                 clientGradeTv.setText(data.getStringExtra("typeName"));
                 grade = data.getStringExtra("typeId");
                 break;
             case RequestAndResultCode.CarrosserieDescribe_Back_rearApronBar://多选价格
                 carPriceId =  data.getStringArrayListExtra("typeIdList");
                 Logger.d("carPriceId=="+carPriceId.size());
                 carPriceTv.setText(data.getStringExtra("Name"));
                 break;
             case RequestAndResultCode.CarrosserieDescribe_Back_spareBar://多
                 carTypeTv.setText(data.getStringExtra("Name"));
                 carTypeId =  data.getStringArrayListExtra("typeIdList");
                 Logger.d("carTypeId=="+carPriceId.size());
                 break;
             case RequestAndResultCode.CarrosserieDescribe_Back_rightRearInnerPlate://车龄
                 carAgeTv.setText(data.getStringExtra("Name"));
                 carAgeId =  data.getStringArrayListExtra("typeIdList");
                 Logger.d("carAgeId=="+carPriceId.size());
                 break;

         }
    }

}
